import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:decimal/decimal.dart';
import 'package:ecy_app_flutter/constant/constant.dart';
import 'package:ecy_app_flutter/model/EcyApiCommonPage.dart';
import 'package:ecy_app_flutter/routes/my/model/Logistics.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../EcyRouter.dart';
import '../../constant/EcyEventConsnt.dart';
import '../../ecycommon/EcyAPI.dart';
import '../../ecycommon/EcyEventBus.dart';
import '../../ecycommon/EcyRequestBaseManager.dart';
import '../../ecycommon/utils/EcyAlipayUtil.dart';
import '../../ecycommon/utils/EcyQQUtil.dart';
import '../../ecycommon/utils/EcyStorage.dart';
import '../../ecycommon/utils/EcyWxUtil.dart';
import '../../model/EcyApiCommonResponse.dart';
import '../../model/EcyLocationModel.dart';
import '../login/common/DateUtil.dart';
import 'detail/EcyOrderInfoPage.dart';
import 'model/EcyMyOrder.dart';
import 'model/EcyMyOrderCommodity.dart';

class EcyMyOrderPage extends StatefulWidget {
  int index = 0;
  EcyMyOrderPage(this.index);

  @override
  _EcyMyOrderPageState createState() => _EcyMyOrderPageState(this.index);
}

class _EcyMyOrderPageState extends State<EcyMyOrderPage>
    with SingleTickerProviderStateMixin {
  int _index = 0;

  _EcyMyOrderPageState(this._index);

  List<EcyMyOrder> _orderList = [];
  final List<String> tabs = [
    '全部',
    '拼团中',
    '待付款',
    '待发货',
    '自提',
    '待收货',
    '待评价',
    '售后'
  ];
  final _orderStatusList = ["", "2", "0", "3", "", "4", "5", "5"];
  final _orderStatusMap = {
    0: "待付款",
    1: "买家已付款",
    2: "拼团中",
    3: "待发货",
    4: "已发货",
    5: "已完成",
    6: "已取消",
    7: "交易关闭",
    8: "拼团失败",
    9: "等待商家处理",
    10: "已退款",
    11: "待核销"
  };
  final logisticsStatusMap = {
    "WAIT_ACCEPT": "待揽收",
    "ACCEPT": "已揽收",
    "TRANSPORT": "运输中",
    "DELIVERING": "派件中",
    "AGENT_SIGN": "已代签收",
    "SIGN": "已签收",
    "FAILED": "包裹异常",
  };
  late TabController _tabController;
  final List<ScrollController> _tabScrollControllers = [];
  int _currentPage = 1;
  bool _hasMore = false;
  bool showToTopBtn = false;

  // 添加刷新控制器
  late List<RefreshController> _refreshControllers;

  @override
  void initState() {
    super.initState();

    // 初始化刷新控制器
    _refreshControllers = List.generate(
      tabs.length,
      (index) => RefreshController(initialRefresh: false),
    );

    _tabController = TabController(length: tabs.length, vsync: this);
    _tabController.addListener(() {
      if (_tabController.animation!.value == _tabController.index) {
        _handleTabSelection(_tabController.index); //获取点击或滑动页面的索引值
      }
    });

    // 初始化每个 Tab 页的控制器
    for (int i = 0; i < tabs.length; i++) {
      ScrollController scrollController = ScrollController();
      _tabScrollControllers.add(scrollController);
      scrollController.addListener(() {
        if (scrollController.position.pixels >=
            scrollController.position.maxScrollExtent) {
          _onLoadMore(i);
        }

        if (scrollController.offset < 300 && showToTopBtn) {
          setState(() {
            showToTopBtn = false;
          });
        } else if (scrollController.offset >= 300 && showToTopBtn == false) {
          setState(() {
            showToTopBtn = true;
          });
        }
      });
    }
    _tabController.index = _index;
    requestData();
  }

  @override
  void dispose() {
    // 清理控制器，避免内存泄漏
    _tabController.dispose();
    // 释放所有控制器
    for (var controller in _tabScrollControllers) {
      controller.dispose();
    }
    // 释放刷新控制器
    for (var controller in _refreshControllers) {
      controller.dispose();
    }
    super.dispose();
  }

  @override
  Future<void> requestData({int pageIndex = 1}) async {
    Map<String, dynamic> body = {
      "pageSize": 10,
      "pageIndex": pageIndex,
      "orderStatus": _index == 7 ? null : _orderStatusList[_index],
      "orderStatusList": _index == 7 ? [5, 9, 10] : null,
      "shippingMethod": _index == 4 ? 1 : null,
    };
    var response =
    await EcyRequestbasemanager().get("/app/api/app/user/order", body);
    if (response != null) {
      var myOrderRespModel =
      EcyApiCommonResponse.fromJson(response, (response) => json);
      if (myOrderRespModel.code == 0 || myOrderRespModel.code == 200) {
        EcyApiCommonPage<EcyMyOrder> commonPage = EcyApiCommonPage.fromJson(
            response["data"], (json) => EcyMyOrder.fromJson(json));
        setState(() {
          _hasMore = (commonPage.pages ?? 0) > _currentPage;
          _currentPage = commonPage.current ?? 0;
          if (_currentPage == 1) {
            _orderList = commonPage.records ?? [];
          } else {
            _orderList.addAll(commonPage.records ?? []);
          }
        });
      } else {
        EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 1));
      }
      EcyEventBus().emit(EcyEventConst.kOnOrder);
    }
  }

  _handleTabSelection(int index) {
    _index = index;
    requestData();
  }

  // 修改刷新方法
  Future<void> _onRefresh(int tabIndex) async {
    _currentPage = 1;
    await requestData(pageIndex: _currentPage);
    _refreshControllers[tabIndex].refreshCompleted();
    // 重置上拉加载状态
    if (_hasMore) {
      _refreshControllers[tabIndex].loadComplete();
    } else {
      _refreshControllers[tabIndex].loadNoData();
    }
  }

  // 修改加载更多方法
  Future<void> _onLoadMore(int tabIndex) async {
    if (_hasMore) {
      _currentPage++;
      await requestData(pageIndex: _currentPage);
      _refreshControllers[tabIndex].loadComplete();
    } else {
      _refreshControllers[tabIndex].loadNoData();
    }
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
        length: tabs.length,
        child: Scaffold(
          backgroundColor: const Color(0xFFF5F5F5),
          appBar: AppBar(
              title: Text('我的订单',
                  style: TextStyle(
                      fontFamily: "PingFang SC",
                      fontWeight: FontWeight.w700,
                      fontSize: 16.sp,
                      color: const Color(0xFF262626))),
              centerTitle: true,
              backgroundColor: Colors.white,
              leadingWidth: 50.w,
              scrolledUnderElevation: 0,
              leading: GestureDetector(
                behavior: HitTestBehavior.translucent,
                onTap: () {
                  EcyRouter.pop(context, "");
                },
                child: Align(
                  alignment: Alignment.centerRight,
                  child: Image.asset(
                    "assets/images/ic_back.png",
                    width: 30.w,
                  ),
                ),
              ),
              // actions: <Widget>[
              //   //导航栏右侧菜单
              //   IconButton(icon: const Icon(Icons.search), onPressed: () {}),
              // ],
              bottom: PreferredSize(
                preferredSize: const Size.fromHeight(40),
                child: Material(
                  color: const Color(0xFFF5F5F5),
                  child: TabBar(
                    controller: _tabController,
                    isScrollable: true,
                    tabAlignment: TabAlignment.center,
                    labelStyle: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w700,
                        fontSize: 18.sp,
                        color: const Color(0xFF262626)),
                    unselectedLabelStyle: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w700,
                        fontSize: 14.sp,
                        color: const Color(0xFF8C8C8C)),
                    tabs: tabs.map((e) => Tab(text: e)).toList(),
                    indicatorColor: Colors.transparent,
                    overlayColor:
                        const WidgetStatePropertyAll(Colors.transparent),
                    dividerHeight: 0,
                  ),
                ),
              )),
          body: TabBarView(
              controller: _tabController, children: _getPagesWidget(tabs)),
          floatingActionButton: !showToTopBtn
              ? null
              : FloatingActionButton(
                  mini: true,
                  backgroundColor: Colors.white,
                  onPressed: () {
                    //返回到顶部时执行动画
                    _tabScrollControllers[_tabController.index].animateTo(
                      0.0,
                      duration: const Duration(milliseconds: 200),
                      curve: Curves.ease,
                    );
                  },
                  child: const Icon(Icons.arrow_upward)),
        ));
  }

  List<Widget> _getPagesWidget(List<String> tabs) {
    return tabs.map((e) {
      final tabIndex = tabs.indexOf(e);
      if (_tabController.index != tabIndex || _orderList.isEmpty) {
        return SmartRefresher(
          enablePullDown: true,
          enablePullUp: false,
          header: const ClassicHeader(
            refreshStyle: RefreshStyle.Follow,
            idleText: '下拉刷新',
            refreshingText: '加载中...',
            completeText: '刷新完成',
            failedText: '刷新失败',
            textStyle: TextStyle(color: Color(0xFF8C8C8C), fontSize: 14),
            releaseText: '松开刷新',
            iconPos: IconPosition.top,
            spacing: 8,
          ),
          controller: _refreshControllers[tabIndex],
          onRefresh: () => _onRefresh(tabIndex),
          child: CustomScrollView(
            slivers: [
              SliverFillRemaining(
                child: SizedBox(
                  height: MediaQuery.of(context).size.height - 200.w,
                  child: Column(
                    children: [
                      Padding(padding: EdgeInsets.only(top: 50.w)),
                      Center(
                        child: Image.asset(
                          'assets/images/empty/ic_empty_orders.png',
                          width: 250.w,
                          height: 250.w,
                        ),
                      ),
                      Text('暂无订单',
                          style: TextStyle(
                              fontFamily: "PingFang SC",
                              fontWeight: FontWeight.w500,
                              fontSize: 18.sp,
                              color: const Color(0xFF8C8C8C))),
                    ],
                  ),
                ),
              ),
            ],
          ),
        );
      }
      return SmartRefresher(
        enablePullDown: true,
        enablePullUp: true,
        header: const ClassicHeader(
          refreshStyle: RefreshStyle.Follow,
          idleText: '下拉刷新',
          refreshingText: '加载中...',
          completeText: '刷新完成',
          failedText: '刷新失败',
          textStyle: TextStyle(color: Color(0xFF8C8C8C), fontSize: 14),
          releaseText: '松开刷新',
          iconPos: IconPosition.top,
          spacing: 8,
        ),
        footer: CustomFooter(
          builder: (BuildContext context, LoadStatus? mode) {
            Widget body;
            if (mode == LoadStatus.idle) {
              body = const Text("上拉加载更多",
                  style: TextStyle(color: Color(0xFF8C8C8C)));
            } else if (mode == LoadStatus.loading) {
              body = const CircularProgressIndicator(
                valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFEA4B9B)),
              );
            } else if (mode == LoadStatus.failed) {
              body = const Text("加载失败，点击重试",
                  style: TextStyle(color: Color(0xFF8C8C8C)));
            } else if (mode == LoadStatus.canLoading) {
              body = const Text("松手加载更多",
                  style: TextStyle(color: Color(0xFF8C8C8C)));
            } else {
              body = const Text("没有更多订单了",
                  style: TextStyle(color: Color(0xFF8C8C8C)));
            }
            return SizedBox(
              height: 35.w,
              child: Center(child: body),
            );
          },
        ),
        controller: _refreshControllers[tabIndex],
        onRefresh: () => _onRefresh(tabIndex),
        onLoading: () => _onLoadMore(tabIndex),
        child: ListView.builder(
          physics: const ClampingScrollPhysics(),
          padding: const EdgeInsets.fromLTRB(10, 0, 10, 10),
          itemCount: _orderList.length,
          itemBuilder: (context, index) {
            EcyMyOrder currOrder = _orderList[index];
            return _buildOrderCard(currOrder);
          },
        ),
      );
    }).toList();
  }

  Widget _buildOrderCard(EcyMyOrder myOrder) {
    List<EcyMyOrderCommodity> commodities = myOrder.commodities ?? [];
    if (commodities.isEmpty) {
      return Container();
    }

    for (var e in commodities) {
      e.orderId = myOrder.orderId;
    }
    var totalPrice = commodities
            .map((e) => Decimal.parse((e.totalPrice ?? 0.0).toString()))
            .reduce((value1, value2) => value1 + value2) +
        Decimal.parse((myOrder.postage ?? 0.0).toString());
    EcyMyOrderCommodity orderCommodity = commodities[0];
    return GestureDetector(
        child: Card(
          color: Colors.white,
          elevation: 0,
          margin: const EdgeInsets.only(bottom: 8),
          child: Padding(
            padding: const EdgeInsets.all(8),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          SizedBox(
                            height: 24.w,
                            width: 24.w,
                            child: ClipRRect(
                                borderRadius: BorderRadius.circular(50.0),
                                child: CachedNetworkImage(
                                    imageUrl: orderCommodity.shopIcon ?? "",
                                    imageBuilder: (context, imageProvider) =>
                                        Container(
                                          decoration: BoxDecoration(
                                              borderRadius: BorderRadius.only(
                                                  topRight:
                                                      Radius.circular(8.r),
                                                  topLeft:
                                                      Radius.circular(8.r)),
                                              image: DecorationImage(
                                                  image: imageProvider,
                                                  fit: BoxFit.cover)),
                                        ),
                                    errorWidget: (context, url, error) =>
                                        Image.asset(
                                            "assets/images/ic_head.jpg"))),
                          ),
                          const Padding(padding: EdgeInsets.only(left: 8)),
                          Text(orderCommodity.shopName ?? '***',
                              style: TextStyle(
                                  fontFamily: "PingFang SC",
                                  fontWeight: FontWeight.w700,
                                  fontSize: 14.sp,
                                  color: const Color(0xFF262626))),
                        ]),
                    Text(
                        (_index == 4 && myOrder.orderStatus == 5)
                            ? "已核销"
                            : _orderStatusMap[myOrder.orderStatus] ?? '***',
                        style: TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w700,
                            fontSize: 16.sp,
                            color: const Color(0xFFF55F4E))),
                  ],
                ),
                const Padding(padding: EdgeInsets.only(top: 8)),
                _getImagesBody(orderCommodity, commodities, totalPrice,
                    myOrder.orderType == "1" || myOrder.orderType == "4"),
                if (commodities.length == 1) _getGroupBuyContainer(myOrder),
                const Padding(padding: EdgeInsets.only(top: 8)),
                Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                  Row(mainAxisAlignment: MainAxisAlignment.end, children: [
                    Text(
                        myOrder.shippingMethod == 1
                            ? "自提"
                            : totalPrice >= Decimal.parse("150")
                                ? '包邮'
                                : '含运费',
                        style: TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w500,
                            fontSize: 14.sp,
                            color: const Color(0xFF8C8C8C)),
                        textAlign: TextAlign.right),
                    const Padding(padding: EdgeInsets.only(right: 12)),
                    Text('实付款￥$totalPrice',
                        style: TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w700,
                            fontSize: 14.sp,
                            color: const Color(0xFF262626)),
                        textAlign: TextAlign.right),
                  ]),
                ]),
                const Padding(padding: EdgeInsets.only(top: 14)),
                _getButtonBody(myOrder, commodities),
              ],
            ),
          ),
        ),
        onTap: () {
          // 进入订单详情
          // EcyRouter.push(context, EcyRouter.orderInfoPage, myOrder.orderId);
          Navigator.push(context, MaterialPageRoute(builder: (context) {
            return EcyOrderInfoPage(myOrder.orderId ?? "", (orderStatus) {
              // 取消订单
              if (orderStatus == "6") {
                if (_index != 0) {
                  setState(() {
                    _orderList
                        .removeWhere((e) => e.orderCode == myOrder.orderCode);
                  });
                } else {
                  setState(() {
                    myOrder.orderStatus = orderStatus;
                  });
                }
              }
              // 待退款
              if (orderStatus == "9") {
                if (_index != 0) {
                  setState(() {
                    _orderList
                        .removeWhere((e) => e.orderCode == myOrder.orderCode);
                  });
                } else {
                  setState(() {
                    myOrder.orderStatus = orderStatus;
                  });
                }
              }
            });
          }));
        });
  }

  Widget _getImagesBody(
      EcyMyOrderCommodity orderCommodity,
      List<EcyMyOrderCommodity> commodities,
      Decimal totalPrice,
      bool isGroupBuy) {
    var defaultImage = Image.asset(
      "assets/images/app_icon.png",
      width: 70.w,
      height: 70.w,
    );
    if (commodities.length == 1) {
      return LayoutBuilder(
        builder: (context, constraints) {
          return Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              SizedBox(
                height: 70.w,
                width: 70.w,
                child: ClipRRect(
                    borderRadius: BorderRadius.circular(8.r),
                    child: CachedNetworkImage(
                        width: 70.w,
                        height: 70.w,
                        imageUrl: commodities[0].image ?? "",
                        imageBuilder: (context, imageProvider) => Container(
                              decoration: BoxDecoration(
                                  borderRadius:
                                      BorderRadius.all(Radius.circular(8.r)),
                                  image: DecorationImage(
                                      image: imageProvider, fit: BoxFit.cover)),
                            ),
                        errorWidget: (context, url, error) => defaultImage)),
              ),
              Expanded(
                child: Padding(
                  padding: const EdgeInsets.only(left: 8),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          if (isGroupBuy)
                            Container(
                              decoration: BoxDecoration(
                                gradient: const LinearGradient(colors: [
                                  Color(0xFFFF7BBE),
                                  Color(0xFFFF3E9F)
                                ]),
                                borderRadius: BorderRadius.circular(8.0),
                              ),
                              padding:
                                  const EdgeInsets.symmetric(horizontal: 4),
                              child: Text(
                                "拼团",
                                style: TextStyle(
                                  fontFamily: "PingFang SC",
                                  fontWeight: FontWeight.w500,
                                  fontSize: 10.sp,
                                  color: const Color(0xFFFFFFFF),
                                ),
                              ),
                            ),
                          const SizedBox(width: 4),
                          Expanded(
                            child: Text(
                              orderCommodity.commodityName ?? '***',
                              style: TextStyle(
                                fontFamily: "PingFang SC",
                                fontWeight: FontWeight.w700,
                                fontSize: 14.sp,
                                color: const Color(0xFF262626),
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                        ],
                      ),
                      const SizedBox(height: 4),
                      Padding(
                        padding: const EdgeInsets.only(
                          left: 4,
                        ),
                        child: Text(
                          orderCommodity.name ?? '***',
                          style: TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w500,
                            fontSize: 14.sp,
                            color: const Color(0xFF8C8C8C),
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              SizedBox(
                width: 80.w,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Text('￥$totalPrice',
                        style: TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w700,
                            fontSize: 14.sp,
                            color: const Color(0xFF262626)),
                        textAlign: TextAlign.right),
                    const SizedBox(height: 4),
                    Text('x${orderCommodity.num ?? 0}',
                        style: TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w500,
                            fontSize: 14.sp,
                            color: const Color(0xFF8C8C8C)),
                        textAlign: TextAlign.right),
                  ],
                ),
              ),
            ],
          );
        },
      );
    } else {
      var count = commodities.length;
      if (count > 3) {
        commodities = commodities.sublist(0, 3);
      }
      List<Widget> imageWidgets = commodities.map((e) {
        return SizedBox(
          height: 70.w,
          width: 70.w,
          child: ClipRRect(
              borderRadius: BorderRadius.circular(8.r),
              child: CachedNetworkImage(
                  width: 70.w,
                  height: 70.w,
                  imageUrl: e.image ?? "",
                  imageBuilder: (context, imageProvider) => Container(
                        decoration: BoxDecoration(
                            borderRadius:
                                BorderRadius.all(Radius.circular(8.r)),
                            image: DecorationImage(
                                image: imageProvider, fit: BoxFit.cover)),
                      ),
                  errorWidget: (context, url, error) => defaultImage)),
        );
      }).toList();
      return Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: Wrap(
              spacing: 8.0,
              children: imageWidgets,
            ),
          ),
          SizedBox(
            width: 80.w,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.end,
              children: [
                Text('￥$totalPrice',
                    style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w700,
                        fontSize: 14.sp,
                        color: const Color(0xFF262626)),
                    textAlign: TextAlign.right),
                const SizedBox(height: 4),
                Text('共$count件',
                    style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w500,
                        fontSize: 14.sp,
                        color: const Color(0xFF8C8C8C)),
                    textAlign: TextAlign.right),
              ],
            ),
          ),
        ],
      );
    }
  }

  Container _getGroupBuyContainer(EcyMyOrder myOrder) {
    if (myOrder.groupBuyItems == null || myOrder.groupBuyItems!.isEmpty) {
      return Container();
    }

    var groupBuyId = myOrder.groupBuyItems![0].groupBuyId;
    if (myOrder.orderType == "1" || myOrder.orderType == "4") {
      var type = myOrder.orderType == "1" ? "1" : "5";
      if (myOrder.orderStatus == 2) {
        var waitingNum =
            myOrder.groupBuyItems!.where((e) => e.userId == null).length;
        return Container(
          height: 32.w,
          margin: const EdgeInsets.only(
            top: 8,
          ),
          padding: const EdgeInsets.only(
            left: 8,
          ),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(8.r)),
            color: const Color.fromARGB(15, 255, 83, 169),
          ),
          child: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              EcyRouter.push(
                  context,
                  '${Constant.H5_BASE_URL}groupBuying.html?groupBuyId=$groupBuyId&type=$type&domain=${Constant.API_BASE_URL}&timestamp=${DateUtil.timestamp()}',
                  {});
            },
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Image.asset('assets/images/warning@2x.png', width: 17.w),
                    Text(' 待分享，还差$waitingNum位即可成团！',
                        style: TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w500,
                          fontSize: 14.sp,
                          color: const Color(0xFFEA4B9B),
                        )),
                  ],
                ),
                const Padding(
                    padding: EdgeInsets.only(right: 8),
                    child: Image(
                        image: AssetImage('assets/images/rightArrow.png'),
                        width: 12)),
              ],
            ),
          ),
        );
      } else if (myOrder.orderStatus == 3) {
        var type = myOrder.orderType == "1" ? "4" : "6";
        return Container(
          height: 32.w,
          margin: const EdgeInsets.only(
            top: 8,
          ),
          padding: const EdgeInsets.only(
            left: 8,
          ),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(8.r)),
            color: const Color.fromARGB(15, 70, 219, 122),
          ),
          child: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              EcyRouter.push(
                  context,
                  '${Constant.H5_BASE_URL}groupBuying.html?groupBuyId=$groupBuyId&type=$type&domain=${Constant.API_BASE_URL}&timestamp=${DateUtil.timestamp()}',
                  {});
            },
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Row(
                  children: [
                    Image.asset('assets/images/check-circle@2x.png',
                        width: 17.w),
                    Text(" 拼团成功，盲盒正在快马加鞭赶来~",
                        style: TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w500,
                          fontSize: 14.sp,
                          color: const Color(0xFF46DB7A),
                        )),
                  ],
                ),
                const Padding(
                    padding: EdgeInsets.only(right: 8),
                    child: Image(
                        image: AssetImage('assets/images/rightArrow.png'),
                        width: 12))
              ],
            ),
          ),
        );
      } else if (myOrder.orderStatus == 8) {
        var type = myOrder.orderType == "1" ? "3" : "7";
        return Container(
          height: 32.w,
          margin: const EdgeInsets.only(
            top: 8,
          ),
          padding: const EdgeInsets.only(
            left: 8,
          ),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(8.r)),
            color: const Color.fromARGB(15, 245, 95, 78),
          ),
          child: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              EcyRouter.push(
                  context,
                  '${Constant.H5_BASE_URL}groupBuying.html?groupBuyId=$groupBuyId&type=$type&domain=${Constant.API_BASE_URL}&timestamp=${DateUtil.timestamp()}',
                  {});
            },
            child: Row(
              children: [
                Row(
                  children: [
                    Image.asset('assets/images/x-circle@2x.png', width: 17.w),
                    Text(" 拼团失败，多分享可以增加成功几率哦~",
                        style: TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w500,
                          fontSize: 14.sp,
                          color: const Color(0xFFF55F4E),
                        )),
                  ],
                ),
                const Padding(
                    padding: EdgeInsets.only(right: 8),
                    child: Image(
                        image: AssetImage('assets/images/rightArrow.png'),
                        width: 12)),
              ],
            ),
          ),
        );
      }
    }

    return Container();
  }

  Future<String> getPayInfo(EcyMyOrder order) async {
    var response = await EcyRequestbasemanager().post(EcyAPI.pay.url,
        {"channel": order.payChannel, "orderId": order.orderId});
    return response["data"];
  }

  /// 去支付
  _pay(EcyMyOrder order) async {
    EasyLoading.show(status: '支付中...', dismissOnTap: false);
    try {
      EcyStorage.setString(EcyEventConst.kPayedOrderId, order.orderId);
      if (order.payChannel == 1) {
        dynamic payInfo = await getPayInfo(order);
        EcyAlipayUtil().startPay(payInfo, context);
      } else {
        String payInfo = await getPayInfo(order);
        bool wechatFlag = await EcyWxUtil().pay(json.decode(payInfo), context);
        if (!wechatFlag) {
          EasyLoading.showToast("微信支付失败，请稍后再试",
              duration: const Duration(seconds: 2));
        }
      }
    } catch (e) {
      EasyLoading.showToast("支付失败，请稍后再试", duration: const Duration(seconds: 2));
    } finally {
      EasyLoading.dismiss();
    }
  }

  /// 确认收货
  _sign(EcyMyOrder order) async {
    try {
      var response = await EcyRequestbasemanager()
          .post(EcyAPI.sign.url, {"orderCode": order.orderCode});
      if (response != null) {
        var commonResponse =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          if (_index != 0) {
            setState(() {
              _orderList.removeWhere((e) => e.orderCode == order.orderCode);
            });
          } else {
            setState(() {
              order.orderStatus = 5;
            });
          }
        } else {
          EasyLoading.showToast(commonResponse.msg ?? "请稍后再试",
              duration: const Duration(seconds: 2));
        }
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
  }

  /// 查看物流
  _logistics(EcyMyOrder order) async {
    List<Map<String, dynamic>> response = [];
    try {
      response = await Future.wait([
        EcyRequestbasemanager()
            .get("${EcyAPI.logistics.url}/${order.logisticsCode}", {}),
        EcyRequestbasemanager()
            .get("${EcyAPI.address.url}/${order.shippingId}", {}),
      ]);
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }

    if (response.isNotEmpty) {
      var logisticsResp = response[0];
      if (logisticsResp != null) {
        var logisticsCommonResponse = EcyApiCommonResponse.fromJson(
            logisticsResp, (logisticsResp) => json);
        if (logisticsCommonResponse.code == 0 ||
            logisticsCommonResponse.code == 200) {
          List<Logistics> logisticsList =
              ((response[0]["data"] ?? []) as List<dynamic>)
                  .map((e) => Logistics.fromJson(e as Map<String, dynamic>))
                  .toList();
          if (logisticsList.isEmpty) {
            EasyLoading.showToast("物流信息待更新",
                duration: const Duration(seconds: 1));
            return;
          }

          var addressResp = response[1];
          EcyLocationModel? address;
          if (addressResp != null) {
            var addressCommonResponse = EcyApiCommonResponse.fromJson(
                addressResp, (addressResp) => json);
            if (addressCommonResponse.code == 0 ||
                addressCommonResponse.code == 200) {
              address = EcyLocationModel.fromJson(response[1]["data"] ?? {});
            }
          }

          showModalBottomSheet(
            context: context,
            backgroundColor: Colors.transparent,
            isScrollControlled: true,
            builder: (context) => Container(
              height: MediaQuery.of(context).size.height * 0.7,
              decoration: const BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    padding:
                        EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
                    decoration: BoxDecoration(
                      border: Border(
                        bottom: BorderSide(
                          color: Colors.grey.withOpacity(0.1),
                        ),
                      ),
                    ),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text(
                          "物流信息",
                          style: TextStyle(
                            fontFamily: "PingFang SC",
                            fontSize: 18.sp,
                            fontWeight: FontWeight.w600,
                            color: const Color(0xFF262626),
                          ),
                        ),
                        GestureDetector(
                          onTap: () => Navigator.pop(context),
                          child: Icon(Icons.close, size: 24.w),
                        ),
                      ],
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(left: 16.w, top: 8.h, bottom: 8.h),
                    child: Text(
                      "收货地址：${address?.provinceName}${address?.cityName}${address?.areaName}${address?.detail}",
                      style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w600,
                        fontSize: 16.sp,
                        color: const Color(0xFF262626),
                      ),
                    ),
                  ),
                  Padding(padding: EdgeInsets.only(bottom: 18.h)),
                  Expanded(
                    child: ListView.builder(
                      padding: EdgeInsets.symmetric(horizontal: 16.w),
                      itemCount: logisticsList.length,
                      itemBuilder: (context, index) {
                        final logistics = logisticsList[index];
                        final isFirst = index == 0;
                        final isLast = index == logisticsList.length - 1;

                        return Container(
                          padding: EdgeInsets.symmetric(vertical: 2.h),
                          child: Row(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              // 时间轴
                              SizedBox(
                                width: 24.w,
                                child: Column(
                                  children: [
                                    Container(
                                      width: 12.w,
                                      height: 12.w,
                                      decoration: BoxDecoration(
                                        color: isFirst
                                            ? const Color(0xFFEA4B9B)
                                            : Colors.grey.withOpacity(0.3),
                                        shape: BoxShape.circle,
                                      ),
                                    ),
                                    if (!isLast || logisticsList.length == 1)
                                      Container(
                                        width: 2.w,
                                        height: 110.h,
                                        color: Colors.grey.withOpacity(0.3),
                                      ),
                                  ],
                                ),
                              ),
                              SizedBox(width: 12.w),
                              // 物流信息
                              Expanded(
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Text(
                                      logisticsStatusMap[
                                              logistics.logisticsStatus] ??
                                          "",
                                      style: TextStyle(
                                        fontFamily: "PingFang SC",
                                        fontWeight: FontWeight.w600,
                                        fontSize: 16.sp,
                                        color: const Color(0xFF262626),
                                      ),
                                    ),
                                    SizedBox(height: 4.h),
                                    Text(
                                      logistics.logisticsDesc ?? "",
                                      style: TextStyle(
                                        fontFamily: "PingFang SC",
                                        fontWeight: FontWeight.w500,
                                        fontSize: 16.sp,
                                        color: const Color(0xFF262626),
                                      ),
                                    ),
                                    SizedBox(height: 4.h),
                                    Text(
                                      logistics.createTime
                                              ?.replaceFirst("T", "") ??
                                          "",
                                      style: TextStyle(
                                        fontFamily: "PingFang SC",
                                        fontWeight: FontWeight.w400,
                                        fontSize: 14.sp,
                                        color: const Color(0xFF8C8C8C),
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        );
                      },
                    ),
                  ),
                ],
              ),
            ),
          );
        } else {
          EasyLoading.showToast("物流信息待更新",
              duration: const Duration(seconds: 1));
        }
      }
    }
  }

  /// 加入购物车
  _addCart(EcyMyOrder order) async {
    try {
      var carts = (order.commodities ?? []).map((e) {
        return {
          "commoditySkuId": e.id,
          "commoditySkuCode": e.code,
          "commoditySkuQuantity": e.num,
        };
      }).toList();
      var response = await EcyRequestbasemanager()
          .post(EcyAPI.addCart.url, {"carts": carts});
      if (response != null) {
        var commonResponse =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EcyRouter.pushNoParams(context, EcyRouter.goodsCartHomePage);
        } else {
          EasyLoading.showToast(commonResponse.msg ?? "请稍后再试",
              duration: const Duration(seconds: 2));
        }
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
  }

  /// 取消订单
  _cancelOrder(String orderCode) async {
    try {
      var response = await EcyRequestbasemanager()
          .get(EcyAPI.cancelOrder.url + orderCode, {});
      if (response != null) {
        var commonResponse =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EasyLoading.showToast("已取消", duration: const Duration(seconds: 2));
          if (_index != 0) {
            setState(() {
              _orderList.removeWhere((e) => e.orderCode == orderCode);
            });
          } else {
            setState(() {
              var order =
                  _orderList.firstWhere((e) => e.orderCode == orderCode);
              order.orderStatus = 6;
            });
          }
        } else {
          EasyLoading.showToast(commonResponse.msg ?? "请稍后再试",
              duration: const Duration(seconds: 2));
        }
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
  }

  /// 再次拼团
  _createGroupBuy(EcyMyOrder order) async {
    if (order.commodities == null || order.commodities!.isEmpty) {
      EasyLoading.showToast("商品已失效", duration: const Duration(seconds: 2));
      return;
    }
    var goods = [];
    for (var item in order.commodities!) {
      var num = item.num ?? 1;
      var singlePrice = Decimal.parse((item.price ?? 0.00).toString());
      var totalPrice = Decimal.parse(num.toString()) * singlePrice;
      goods.add({
        "skuId": item.id,
        "price": double.parse(singlePrice.toString()),
        "salePrice": double.parse(singlePrice.toString()),
        "num": num,
        "totalPrice": double.parse(totalPrice.toString()),
        "imageUrl": item.image,
        "skuName": item.name,
        "selectNum": num
      });
    }
    var msg = {"skuList": goods};
    EcyRouter.push(context, EcyRouter.orderConfirm, json.encode(msg));
  }

  /// 邀请好友
  _inviteFriends(EcyMyOrder order, List<EcyMyOrderCommodity> commoditys) async {
    var commodity = commoditys.isEmpty ? EcyMyOrderCommodity() : commoditys[0];
    String msg =
        '{"shareUrl":"${Constant.H5_BASE_URL}goodsDetailPage.html?goodsid=${commodity.commodityId}&domain=${Uri.encodeComponent(Constant.API_BASE_URL)}&timestamp=${DateTime.now()}&noFlutter=1","shareTitle":"${commodity.commodityName}","shareImageUrl":"${commodity.image}"}';
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (context) => Container(
        height: MediaQuery.of(context).size.height * 0.3,
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(
              padding: EdgeInsets.symmetric(horizontal: 20.w, vertical: 24.h),
              decoration: BoxDecoration(
                border: Border(
                  bottom: BorderSide(
                    color: Colors.grey.withOpacity(0.1),
                  ),
                ),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(
                    padding: const EdgeInsets.only(bottom: 10),
                    child: Text(
                      "邀请好友",
                      style: TextStyle(
                        fontFamily: "PingFang SC",
                        fontWeight: FontWeight.w600,
                        fontSize: 16.sp,
                        color: const Color(0xFF262626),
                      ),
                    ),
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    spacing: 16,
                    children: [
                      GestureDetector(
                        onTap: () {
                          EcyWxUtil.shareText(msg);
                        },
                        child: Column(
                          children: [
                            Image.asset('assets/images/wechat.png',
                                width: 50.w, height: 50.w),
                            Text(
                              "微信",
                              style: TextStyle(
                                fontFamily: "PingFang SC",
                                fontSize: 14.sp,
                                color: const Color(0xFF262626),
                              ),
                            )
                          ],
                        ),
                      ),
                      GestureDetector(
                        onTap: () {
                          EcyQQUtil.shareText(msg);
                        },
                        child: Column(
                          children: [
                            Image.asset('assets/images/qq.png',
                                width: 50.w, height: 50.w),
                            Text(
                              "QQ",
                              style: TextStyle(
                                fontFamily: "PingFang SC",
                                fontSize: 14.sp,
                                color: const Color(0xFF262626),
                              ),
                            )
                          ],
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 申请退款
  _applyRefund(String orderCode) async {
    try {
      var response = await EcyRequestbasemanager().post(EcyAPI.applyRefund.url,
          {"orderCode": orderCode ?? "", "refundReason": "用户申请退款"});
      if (response != null) {
        var commonResponse =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EasyLoading.showToast("请等待商家处理~",
              duration: const Duration(seconds: 2));
          setState(() {
            _orderList.removeWhere((e) => e.orderCode == orderCode);
          });
          EcyEventBus().emit(EcyEventConst.kOnOrder);
        } else {
          EasyLoading.showToast(commonResponse.msg ?? "请稍后再试",
              duration: const Duration(seconds: 2));
        }
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
  }

  /// 删除订单
  _deleteOrder(String? orderId) async {
    if (orderId == null) {
      return;
    }
    try {
      var response = await EcyRequestbasemanager()
          .delete(EcyAPI.deleteOrder.url, [orderId]);
      if (response != null) {
        var commonResponse =
            EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EasyLoading.showToast("订单已删除", duration: const Duration(seconds: 2));
          setState(() {
            _orderList.removeWhere((e) => e.orderId == orderId);
          });
          EcyEventBus().emit(EcyEventConst.kOnOrder);
        } else {
          EasyLoading.showToast(commonResponse.msg ?? "请稍后再试",
              duration: const Duration(seconds: 2));
        }
      }
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    }
  }

  Widget _getButtonBody(
      EcyMyOrder myOrder, List<EcyMyOrderCommodity> commoditys) {
    var orderStatus = myOrder.orderStatus;
    var orderType = myOrder.orderType;
    List<SizedBox> textButtons = [
      // 0|去支付
      SizedBox(
        height: 32.w,
        child: TextButton(
            onPressed: () => _pay(myOrder),
            style: const ButtonStyle(
              alignment: Alignment.center,
              foregroundColor: WidgetStatePropertyAll(Color(0xFFEA4B9B)),
              side: WidgetStatePropertyAll(
                  BorderSide(color: Color(0xFFEA4B9B), width: 1)),
            ),
            child: Text(
              '去支付',
              style: TextStyle(
                fontFamily: "PingFang SC",
                fontWeight: FontWeight.w500,
                fontSize: 14.sp,
                color: const Color(0xFFEA4B9B),
                height: 1,
                leadingDistribution:
                    TextLeadingDistribution.even, // 设置leading策略
              ),
            )),
      ),
      // 1|再次拼团
      SizedBox(
        height: 34.w,
        child: TextButton(
            onPressed: () => _createGroupBuy(myOrder),
            style: const ButtonStyle(
              foregroundColor: WidgetStatePropertyAll(Color(0xFF262626)),
              side: WidgetStatePropertyAll(
                  BorderSide(color: Color(0xFFBFBFBF), width: 0.8)),
            ),
            child: Text(
              '再次拼团',
              style: TextStyle(
                fontFamily: "PingFang SC",
                fontWeight: FontWeight.w500,
                fontSize: 14.sp,
                color: const Color(0xFF262626),
                height: 1,
                leadingDistribution:
                    TextLeadingDistribution.even, // 设置leading策略
              ),
            )),
      ),
      // 2|邀请好友
      SizedBox(
        height: 32.w,
        child: TextButton(
            onPressed: () => _inviteFriends(myOrder, commoditys),
            style: const ButtonStyle(
              alignment: Alignment.center,
              foregroundColor: WidgetStatePropertyAll(Color(0xFFEA4B9B)),
              side: WidgetStatePropertyAll(
                  BorderSide(color: Color(0xFFEA4B9B), width: 1)),
            ),
            child: Text(
              '邀请好友',
              style: TextStyle(
                fontFamily: "PingFang SC",
                fontWeight: FontWeight.w500,
                fontSize: 14.sp,
                color: const Color(0xFFEA4B9B),
                height: 1,
                leadingDistribution:
                    TextLeadingDistribution.even, // 设置leading策略
              ),
            )),
      ),
      // 3|提醒发货
      SizedBox(
        height: 32.w,
        child: TextButton(
            onPressed: () {
              EasyLoading.showToast("已催促店家发货，还请耐心等待。",
                  duration: const Duration(seconds: 2));
            },
            style: const ButtonStyle(
              alignment: Alignment.center,
              foregroundColor: WidgetStatePropertyAll(Color(0xFFEA4B9B)),
              side: WidgetStatePropertyAll(
                  BorderSide(color: Color(0xFFEA4B9B), width: 1)),
            ),
            child: Text(
              '提醒发货',
              style: TextStyle(
                fontFamily: "PingFang SC",
                fontWeight: FontWeight.w500,
                fontSize: 14.sp,
                color: const Color(0xFFEA4B9B),
                height: 1,
                leadingDistribution:
                    TextLeadingDistribution.even, // 设置leading策略
              ),
            )),
      ),
      // 4|查看物流
      SizedBox(
        height: 34.w,
        child: TextButton(
            onPressed: () => _logistics(myOrder),
            style: const ButtonStyle(
              foregroundColor: WidgetStatePropertyAll(Color(0xFF262626)),
              side: WidgetStatePropertyAll(
                  BorderSide(color: Color(0xFFBFBFBF), width: 0.8)),
            ),
            child: Text(
              '查看物流',
              style: TextStyle(
                fontFamily: "PingFang SC",
                fontWeight: FontWeight.w500,
                fontSize: 14.sp,
                color: const Color(0xFF262626),
                height: 1,
                leadingDistribution:
                    TextLeadingDistribution.even, // 设置leading策略
              ),
            )),
      ),
      // 5|确认收货
      SizedBox(
        height: 32.w,
        child: TextButton(
            onPressed: () => _sign(myOrder),
            style: const ButtonStyle(
              alignment: Alignment.center,
              foregroundColor: WidgetStatePropertyAll(Color(0xFFEA4B9B)),
              side: WidgetStatePropertyAll(
                  BorderSide(color: Color(0xFFEA4B9B), width: 1)),
            ),
            child: Text(
              '确认收货',
              style: TextStyle(
                fontFamily: "PingFang SC",
                fontWeight: FontWeight.w500,
                fontSize: 14.sp,
                color: const Color(0xFFEA4B9B),
                height: 1,
                leadingDistribution:
                    TextLeadingDistribution.even, // 设置leading策略
              ),
            )),
      ),
      // 6|加入购物车
      SizedBox(
        height: 34.w,
        child: TextButton(
            onPressed: () => _addCart(myOrder),
            style: const ButtonStyle(
              foregroundColor: WidgetStatePropertyAll(Color(0xFF262626)),
              side: WidgetStatePropertyAll(
                  BorderSide(color: Color(0xFFBFBFBF), width: 0.8)),
            ),
            child: Text(
              '加入购物车',
              style: TextStyle(
                fontFamily: "PingFang SC",
                fontWeight: FontWeight.w500,
                fontSize: 14.sp,
                color: const Color(0xFF262626),
                height: 1,
                leadingDistribution:
                    TextLeadingDistribution.even, // 设置leading策略
              ),
            )),
      ),
      // 7|评价
      SizedBox(
        height: 32.w,
        child: TextButton(
            onPressed: () {
              if (commoditys.isNotEmpty) {
                if (commoditys.length > 1) {
                  EcyRouter.push(
                      context, EcyRouter.orderEvaluateListPage, commoditys);
                } else {
                  EcyRouter()
                      .push(context, EcyRouter.orderEvaluatePage, commoditys[0])
                      .then((newCommodity) {
                    if (newCommodity != null) {
                      setState(() {
                        commoditys[0].evaluateId = newCommodity.evaluateId;
                      });
                    }
                  });
                }
              } else {
                EasyLoading.showToast("请稍后再试",
                    duration: const Duration(seconds: 1));
              }
            },
            style: const ButtonStyle(
              alignment: Alignment.center,
              foregroundColor: WidgetStatePropertyAll(Color(0xFFEA4B9B)),
              side: WidgetStatePropertyAll(
                  BorderSide(color: Color(0xFFEA4B9B), width: 1)),
            ),
            child: Text(
              commoditys.length ==
                      commoditys.where((e) => e.evaluateId != null).length
                  ? '查看评价'
                  : '去评价',
              style: TextStyle(
                fontFamily: "PingFang SC",
                fontWeight: FontWeight.w500,
                fontSize: 14.sp,
                color: const Color(0xFFEA4B9B),
                height: 1,
                leadingDistribution:
                    TextLeadingDistribution.even, // 设置leading策略
              ),
            )),
      ),
      // 8|取消订单
      SizedBox(
        height: 32.w,
        child: TextButton(
            onPressed: () async {
              bool? confirmFlag = await _showConfirmDialog("确定取消订单吗");
              if (confirmFlag != null && confirmFlag) {
                _cancelOrder(myOrder.orderCode ?? "");
              }
            },
            style: const ButtonStyle(
              foregroundColor: WidgetStatePropertyAll(Color(0xFF262626)),
              side: WidgetStatePropertyAll(
                  BorderSide(color: Color(0xFFBFBFBF), width: 0.8)),
            ),
            child: Text(
              '取消订单',
              style: TextStyle(
                fontFamily: "PingFang SC",
                fontWeight: FontWeight.w500,
                fontSize: 14.sp,
                color: const Color(0xFF262626),
                height: 1,
                leadingDistribution:
                    TextLeadingDistribution.even, // 设置leading策略
              ),
            )),
      ),
      // 9|申请退款
      SizedBox(
        height: 32.w,
        child: TextButton(
            onPressed: () async {
              bool? confirmFlag = await _showConfirmDialog("确定申请退款吗");
              if (confirmFlag != null && confirmFlag) {
                _applyRefund(myOrder.orderCode ?? "");
              }
            },
            style: const ButtonStyle(
              foregroundColor: WidgetStatePropertyAll(Color(0xFF262626)),
              side: WidgetStatePropertyAll(
                  BorderSide(color: Color(0xFFBFBFBF), width: 0.8)),
            ),
            child: Text(
              '申请退款',
              style: TextStyle(
                fontFamily: "PingFang SC",
                fontWeight: FontWeight.w500,
                fontSize: 14.sp,
                color: const Color(0xFF262626),
                height: 1,
                leadingDistribution:
                    TextLeadingDistribution.even, // 设置leading策略
              ),
            )),
      ),
      // 10|删除订单
      SizedBox(
        height: 34.w,
        child: TextButton(
            onPressed: () async {
              bool? confirmFlag = await _showConfirmDialog("删除后不可恢复，确定删除吗？");
              if (confirmFlag != null && confirmFlag) {
                _deleteOrder(myOrder.orderId);
              }
            },
            style: const ButtonStyle(
              foregroundColor: WidgetStatePropertyAll(Color(0xFF262626)),
              side: WidgetStatePropertyAll(
                  BorderSide(color: Color(0xFFBFBFBF), width: 0.8)),
            ),
            child: Text(
              '删除订单',
              style: TextStyle(
                fontFamily: "PingFang SC",
                fontWeight: FontWeight.w500,
                fontSize: 14.sp,
                color: const Color(0xFF262626),
                height: 1,
                leadingDistribution:
                    TextLeadingDistribution.even, // 设置leading策略
              ),
            )),
      ),
    ];
    // 待付款
    if (orderStatus == 0) {
      return Row(mainAxisAlignment: MainAxisAlignment.end, children: [
        textButtons[8],
        const Padding(padding: EdgeInsets.only(right: 8)),
        textButtons[0],
      ]);
    } else if (orderStatus == 2) {
      // 拼团中
      return Row(mainAxisAlignment: MainAxisAlignment.end, children: [
        textButtons[1],
        const Padding(padding: EdgeInsets.only(right: 8)),
        textButtons[2],
      ]);
    } else if (orderStatus == 3) {
      // 待发货
      return Row(mainAxisAlignment: MainAxisAlignment.end, children: [
        textButtons[3],
        if (orderType == "0" || orderType == "2" || orderType == "3")
           const Padding(padding: EdgeInsets.only(right: 8)),
        if (orderType == "0" || orderType == "2" || orderType == "3")
          textButtons[9],
      ]);
    } else if (orderStatus == 4) {
      // 已发货-待收货
      return Row(mainAxisAlignment: MainAxisAlignment.end, children: [
        textButtons[4],
        const Padding(padding: EdgeInsets.only(right: 8)),
        textButtons[5],
      ]);
    } else if (orderStatus == 5) {
      // 已完成
      return Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
        SizedBox(
          width: 30.w, // 设置你想要的宽度
          child: PopupMenuButton(
              elevation: 0,
              offset: const Offset(0, -30),
              color: Colors.white,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(10),
              ),
              padding: EdgeInsets.zero,
              menuPadding: EdgeInsets.zero,
              constraints: BoxConstraints(
                maxWidth: 75.w,
              ),
              itemBuilder: (context) => [
                    PopupMenuItem(
                        value: '0',
                        padding: EdgeInsets.zero,
                        height: 30.h,
                        child: DecoratedBox(
                            decoration: BoxDecoration(
                              border: const Border.fromBorderSide(
                                BorderSide(
                                  width: 0.8,
                                  color: Color(0xFFBFBFBF),
                                ),
                              ),
                              borderRadius:
                              BorderRadius.circular(25.0), // 25像素圆角
                            ),
                            child: Padding(
                              padding: const EdgeInsets.symmetric(horizontal: 8.0, vertical: 3.0),
                              child: Text(
                                '删除订单',
                                style: TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontWeight: FontWeight.w500,
                                    fontSize: 14.sp,
                                    color: const Color(0xFF262626)),
                              ),
                            )),
                        onTap: () async {
                          bool? confirmFlag =
                              await _showConfirmDialog("删除后不可恢复，确定删除吗？");
                          if (confirmFlag != null && confirmFlag) {
                            _deleteOrder(myOrder.orderId);
                          }
                        }),
                  ],
              child: Text(
                "更多",
                style: TextStyle(
                    fontFamily: "PingFang SC",
                    fontWeight: FontWeight.w700,
                    fontSize: 14.sp,
                    color: const Color(0xFF262626)),
              )),
        ),
        Row(mainAxisAlignment: MainAxisAlignment.end, children: [
          const Padding(padding: EdgeInsets.only(right: 8)),
          orderType == "1" || orderType == "4"
              ? textButtons[1]
              : textButtons[6],
          const Padding(padding: EdgeInsets.only(right: 8)),
          textButtons[4],
          const Padding(padding: EdgeInsets.only(right: 8)),
          textButtons[7],
        ]),
      ]);
    } else if (orderStatus == 6) {
      // 已取消-交易关闭
      return Row(mainAxisAlignment: MainAxisAlignment.end, children: [
        textButtons[10],
        const Padding(padding: EdgeInsets.only(right: 8)),
        orderType == "1" || orderType == "4" ? textButtons[1] : textButtons[6],
      ]);
    } else if (orderStatus == 7) {
      // 交易关闭
      return Row(mainAxisAlignment: MainAxisAlignment.end, children: [
        textButtons[10],
        const Padding(padding: EdgeInsets.only(right: 8)),
        orderType == "1" || orderType == "4" ? textButtons[1] : textButtons[6],
      ]);
    } else if (orderStatus == 8) {
      // 拼团失败
      return Row(mainAxisAlignment: MainAxisAlignment.end, children: [
        textButtons[1],
      ]);
    } else if (orderStatus == 11) {
      // 待核销
      return Row(mainAxisAlignment: MainAxisAlignment.end, children: [
        textButtons[9],
      ]);
    }

    return Container();
  }

  // 弹出对话框
  Future<bool?> _showConfirmDialog(String content) {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          // title: const Text(''),
          contentPadding: const EdgeInsets.all(0),
          backgroundColor: Colors.white,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8.0),
          ),
          content: SizedBox(
            height: 120.w,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                SizedBox(
                  height: 70.w,
                  child: Padding(
                    padding: EdgeInsets.only(top: 20.w, bottom: 20.w),
                    child: Text(
                      content,
                      style: TextStyle(
                          fontFamily: "PingFang SC",
                          fontWeight: FontWeight.w400,
                          fontSize: 17.sp,
                          color: const Color(0xFF262626)),
                    ),
                  ),
                ),
                const Divider(height: 0, color: Color(0XFFdcdcdc)),
                SizedBox(
                  height: 50.w,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Expanded(
                        flex: 1,
                        child: DecoratedBox(
                          decoration: const BoxDecoration(
                              border: Border(
                            right: BorderSide(
                              width: 1.0,
                              color: Color(0XFFdcdcdc),
                            ),
                          )),
                          child: TextButton(
                            style: const ButtonStyle(
                              alignment: Alignment.center,
                            ),
                            child: Text(
                              '取消',
                              style: TextStyle(
                                  fontFamily: "PingFang SC",
                                  fontWeight: FontWeight.w400,
                                  fontSize: 16.sp,
                                  color: const Color(0xFF262626)),
                            ),
                            onPressed: () =>
                                Navigator.of(context).pop(), // 关闭对话框
                          ),
                        ),
                      ),
                      Expanded(
                        flex: 1,
                        child: TextButton(
                          child: Text(
                            '确认',
                            style: TextStyle(
                                fontFamily: "PingFang SC",
                                fontWeight: FontWeight.w400,
                                fontSize: 16.sp,
                                color: const Color(0xFFEA4B9B)),
                          ),
                          onPressed: () {
                            //关闭对话框并返回true
                            Navigator.of(context).pop(true);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          actionsAlignment: MainAxisAlignment.spaceAround,
          actionsPadding: const EdgeInsets.all(0),
        );
      },
    );
  }
}
